package com.wyy.mall.tiny.service.impl;

import com.wyy.mall.tiny.common.utils.JwtTokenUtil;
import com.wyy.mall.tiny.dao.UmsAdminRoleRelationDao;
import com.wyy.mall.tiny.mbg.mapper.UmsAdminMapper;
import com.wyy.mall.tiny.mbg.model.UmsAdmin;
import com.wyy.mall.tiny.mbg.model.UmsAdminExample;
import com.wyy.mall.tiny.mbg.model.UmsPermission;
import com.wyy.mall.tiny.service.UmsAdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * created by 伍猷煜 on 2021/5/13 23:58 星期四
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);

    @Resource
    private UmsAdminMapper mUmsAdminMapper;
    @Resource
    private UmsAdminRoleRelationDao mUmsAdminRoleRelationDao;

    @Autowired
    private PasswordEncoder mPasswordEncoder;

    @Resource
    private UserDetailsService mUserDetailsService;

    @Autowired
    private JwtTokenUtil mJwtTokenUtil;

    /**
     * 根据用户名获取后台管理员
     *
     * @param username
     * @return
     */
    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> umsAdmins = mUmsAdminMapper.selectByExample(example);
        if (umsAdmins != null && umsAdmins.size() > 0) return umsAdmins.get(0);
        return null;
    }

    /**
     * 注册功能
     *
     * @param umsAdmin
     * @return
     */
    @Override
    public UmsAdmin register(UmsAdmin umsAdmin) {
        UmsAdmin ua = new UmsAdmin();
        BeanUtils.copyProperties(umsAdmin, ua);
        ua.setCreateTime(new Date());
        ua.setStatus(1);

        // 如果存在相同用户名，不允许注册
        if (getAdminByUsername(ua.getUsername()) != null) return null;
        // 密码加密存储
        String encodePassword = mPasswordEncoder.encode(ua.getPassword());
        ua.setPassword(encodePassword);
        // 插入新用户
        mUmsAdminMapper.insert(ua);
        return ua;
    }

    /**
     * 登录功能
     *
     * @param username
     * @param password
     * @return jwt token
     */
    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = mUserDetailsService.loadUserByUsername(username);
            // 判断未加密密码和加密密码是否匹配
            if (!mPasswordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确");
            }
            // 这个步骤是做什么？ 应该是保存登录信息，如果token有效，方便之后访问其他端点无需重新登录验证
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            // 交由SecurityProvider去验证
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = mJwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }

        return token;
    }

    /**
     * 获取用户所有权限（包括角色权限和角色+-权限）
     *
     * @param adminId
     * @return
     */
    @Override
    public List<UmsPermission> getPermissionList(Long adminId) {
        return mUmsAdminRoleRelationDao.getPermissionList(adminId);
    }
}
